import os
import json
from helpers import datetime

def get_env(var_name, required=True):
    value = os.getenv(var_name)
    if required and value is None:
        raise ValueError(f'{var_name} is not configured in the environment.')
    return value

def get_path(prefix, date, format='%Y-%m-%d'):
    if not datetime.is_valid(date, format):
        raise ValueError(f'The date: "{date}" is invalid or does not match the "{format}" format.')
    return os.path.join(get_env(prefix), date[:4], date[:7], f'{date}.json')

def read_json(path):
    if not os.path.exists(path):
        return None
    with open(path, 'r', encoding='utf-8') as f:
        return json.load(f)
    
def write_json(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
